package org.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.*;
import org.example.mapper.*;
import org.example.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ============================================================<br>
 * <p> ProjectName ：dianguanjiaexportdata </p>
 * <p> @author dongjianzhao </p>
 * <p> @date 2023/3/16 </p>
 * <p> @version ：1.0 </p>
 * ============================================================<br>
 * <p>
 * 电管家数据转换到本地数据库后数据适配的逻辑
 * </p>
 * ============================================================<br>
 */
@Service
@Slf4j
public class AdapterImpl {
    @Autowired
    private DgjInitupdcontactMapper dgjInitupdcontactMapper;
    @Autowired
    private DgjAfteraddsearchMapper dgjAfteraddsearchMapper;
    @Autowired
    private DgjQuerysitegridMapper dgjQuerysitegridMapper;
    @Autowired
    private CustInfoMapper custInfoMapper;
    @Autowired
    private CustAddrMapper custAddrMapper;
    @Autowired
    private TaxMapper taxMapper;
    @Autowired
    private DgjQuerydropdownbycodetypeMapper dgjQuerydropdownbycodetypeMapper;
    @Autowired
    private DgjQueryequipmanagementlistMapper dgjQueryequipmanagementlistMapper;
    @Autowired
    private DgjDownMapper dgjDownMapper;
    @Autowired
    private DgjQuerystructurebycustidandsiteidMapper dgjQuerystructurebycustidandsiteidMapper;
    @Autowired
    private IesArEquipmenMapper iesArEquipmenMapper;
    @Autowired
    private IesCustConsnoMapper iesCustConsnoMapper;
    @Autowired
    private IesCustMapper iesCustMapper;
    @Autowired
    private IesServiceMapper iesServiceMapper;
    @Autowired
    private IesStationInfoMapper iesStationInfoMapper;
    @Autowired
    private CmArEquipmentMapper cmArEquipmentMapper;

    public void adapter() {
        SnowFlake sf=new SnowFlake(2,3);
        // addCustInfo(sf);
        // addCustConsno(sf);
        //addStationInfo(sf);
        //addArEqumen(sf);
        // add_cmEquipmnet(sf);
        //  UPDATE `ies_cust_djz20230316` i,`dgj_down` d SET i.type_code_name=d.type_code_name WHERE  d.type='down1' AND i.custids=d.cust_id;
    }
    public void updateServerId() {
        SnowFlake sf=new SnowFlake(2,3);
        updateServerId(sf);
    }

    /**
     * 修改服务商id
     * @param sf
     */
    private void updateServerId(SnowFlake sf) {
        List<IesService> list=iesServiceMapper.selectAll();
        List<IesService> list2=new ArrayList<>();
        list.forEach(l->{
            l.setServerid(sf.nextId());
            l.setServiceencoded(sf.nextId()+"");
            list2.add(l);
        });
//        iesServiceMapper.deleteAll();
        list2.forEach(l->{
            iesServiceMapper.insert(l);
        });
    }

    private void add_cmEquipmnet(SnowFlake sf) {
        List<DgjQueryequipmanagementlist> list = dgjQueryequipmanagementlistMapper.selectAll();
        list.forEach(l->{
            Map<String,Object> params=new HashMap<>();
            params.put("custids", l.getCustId());
            List<IesCust> custInfos1 = iesCustMapper.selectByMap(params);
            if(custInfos1!=null&&custInfos1.size()>0){
                IesCust iesCust = custInfos1.get(0);
                CmArEquipment c=new CmArEquipment();
                c.setEqptId(sf.nextId());
                c.setEqptIds(l.getEquipFilezInfoId());
                /**
                 * 客户标识
                 */
                c.setCustid(Long.valueOf(iesCust.getCustid()));
                /**
                 * 设备编号
                 */
                c.setEqptNo(l.getEquipNo());
                /**
                 * 设备名称
                 */
                c.setEqptName(l.getEquipName());
                /**
                 * 设备类型编号
                 */
                c.setEqptTypeNo(l.getEquipModel());
                /**
                 * 容量-千伏安（KVA）
                 */
            //    c.setCapacity();
                /**
                 * 设备类型
                 */
                c.setDevtype(l.getEquipType());
                /**
                 * 用户标识1
                 */
                c.setConid(l.getConsId()==null||"".equals(l.getConsId())?null:Long.valueOf(l.getConsId()));
                /**
                 * 所属营销户号
                 */
                c.setConsno(l.getConsNo());
                /**
                 * 站点信息 ID
                 */
            //    c.setStationinfoid(l.getSiteId());
                /**
                 * 建筑id
                 */
            //    c.setBuildid();
                /**
                 * 设备状态
                 */
            //    c.setStatus();
                /**
                 * 是否巡检
                 */
             //   c.setIspatrol();
                /**
                 * 安装位置
                 */
            //    c.setUnitposition();
                /**
                 * 生产厂家
                 */
            //    c.setFactory();
                /**
                 * 出厂日期
                 */
              //  c.setMadeDate();
                /**
                 * 投运日期
                 */
             //   c.setRunDate();
                /**
                 * 设备型号
                 */
              //  c.setEqptModeNo();
                /**
                 * 额定功率
                 */
             //   c.setRp();
                /**
                 * 额定电压
                 */
             //   c.setRv();
                /**
                 * 额定电流
                 */
             //   c.setRc();
                /**
                 * 创建人名称
                 */
                c.setCreateByname("电管家");
                /**
                 * 创建用户
                 */
               // c.setCreateBy();
                /**
                 * 创建时间
                 */
                c.setCreateDate(new Date());
                cmArEquipmentMapper.insert(c);
            }

        });
    }

    private void addArEqumen(SnowFlake sf) {
        List<DgjQuerystructurebycustidandsiteid> list=dgjQuerystructurebycustidandsiteidMapper.selectAll();
        list.forEach(l->{


            Map<String,Object> params=new HashMap<>();
            params.put("custids", l.getCustId());
            List<IesCust> custInfos1 = iesCustMapper.selectByMap(params);
            if(custInfos1!=null&&custInfos1.size()>0){
                IesCust iesCust = custInfos1.get(0);
                IesArEquipmen iesArEquipmen=new IesArEquipmen();
                iesArEquipmen.setBuildid(sf.nextId());
                /**
                 * 客户标识
                 */
                iesArEquipmen.setCustid(Long.valueOf(iesCust.getCustid()));
                /**
                 * 父建筑id
                 */
                // iesArEquipmen.setParentbuildid();
                /**
                 * 建筑名称
                 */
                iesArEquipmen.setBuildname(l.getStructureName());
                /**
                 * 建筑类型
                 */
                iesArEquipmen.setBuildtype(l.getStructureTypeName());
                /**
                 * 电压等级
                 */
                 iesArEquipmen.setVoltlevel(l.getVoltLevel());
                /**
                 * 变电容量（kVA）
                 */
                iesArEquipmen.setCapacity(0.0);
                /**
                 * 建筑位置
                 */
                iesArEquipmen.setBuildposition(l.getStructureAddr());
                /**
                 * 面积
                 */
                iesArEquipmen.setBuildarea(l.getStructureSize()==null?0.0:Double.valueOf(l.getStructureSize()));
                /**
                 * 高度
                 */
                iesArEquipmen.setBuildheight(l.getStructureHigh()==null?0.0:Double.valueOf(l.getStructureHigh()));
                /**
                 * 备注
                 */
                iesArEquipmen.setRemarks("");
                /**
                 * 经度
                 */
                iesArEquipmen.setLongtitude(l.getLongData());
                /**
                 * 纬度
                 */
                iesArEquipmen.setLatitude(l.getLatiData());
                /**
                 * 创建人名称
                 */
                iesArEquipmen.setCreateByname("电管家");
                /**
                 * 创建用户
                 */
               // iesArEquipmen.setCreateBy();
                /**
                 * 创建时间
                 */
                iesArEquipmen.setCreateDate(new Date());
                iesArEquipmenMapper.insert(iesArEquipmen);
            }
        });
    }

    private void addStationInfo(SnowFlake sf) {
        List<DgjQuerysitegrid> dgjQuerysitegrids = dgjQuerysitegridMapper.selectAll();
        dgjQuerysitegrids.forEach(dg -> {

            Map<String,Object> params=new HashMap<>();
            params.put("custids", dg.getCustId());
            List<IesCust> custInfos1 = iesCustMapper.selectByMap(params);
            if(custInfos1!=null&&custInfos1.size()>0){
                IesStationInfo iesStationInfo=new IesStationInfo();
                iesStationInfo.setStationinfoid(sf.nextId());
                /**
                 * 站点编号
                 */
                iesStationInfo.setStationNo(dg.getSiteNo());
                IesCust iesCust = custInfos1.get(0);
                String custId="0";
                if(iesCust!=null){
                    custId= iesCust.getCustid();
                }
                /**
                 * 客户标识
                 */
                iesStationInfo.setCustid(Long.valueOf(custId));
                /**
                 * 站点名称
                 */
                iesStationInfo.setStationName(dg.getSiteName());
                /**
                 * 用户标识1
                 */
                iesStationInfo.setConid(0L);
                /**
                 * 用户编号
                 */
                iesStationInfo.setConsno("");
                /**
                 * 接线方式()
                 */
                iesStationInfo.setConnecttype(dg.getWiringCode());
                /**
                 * 电压等级
                 */
                String voltlevel="";
                if("01".equals(dg.getVoltType())){
                    voltlevel="AC00101";
                }
                if("02".equals(dg.getVoltType())){
                    voltlevel="AC00351";
                }
                if("03".equals(dg.getVoltType())){
                    voltlevel="AC01101";
                }
                if("04".equals(dg.getVoltType())){
                    voltlevel="AC02201";
                }
                if("".equals(voltlevel)){
                    voltlevel=dg.getVoltType();
                }
                iesStationInfo.setVoltlevel(voltlevel);
                /**
                 * 地址信息
                 */
                iesStationInfo.setStationaddr(dg.getSiteAddr());
                /**
                 * 联系人
                 */
                iesStationInfo.setContactperson(dg.getContactName());
                /**
                 * 容量（kVA）
                 */
               // iesStationInfo.setCapacity(dg.get);
                /**
                 * 联系电话
                 */
                iesStationInfo.setPersonphone("");
                /**
                 * 经度
                 */
                iesStationInfo.setLongtitude(dg.getLongData());
                /**
                 * 纬度
                 */
                iesStationInfo.setLatitude(dg.getLatiData());
                /**
                 * 创建人名称
                 */
                iesStationInfo.setCreateByname("电管家");
                /**
                 * 创建用户
                 */
               // iesStationInfo.setCreateBy();
                /**
                 * 创建时间
                 */
                iesStationInfo.setCreateDate(new Date());
                iesStationInfoMapper.insert(iesStationInfo);
            }
        });
    }

    private void addCustConsno(SnowFlake sf) {
        List<DgjAfteraddsearch> dgjAfteraddsearches = dgjAfteraddsearchMapper.selectAll();
        dgjAfteraddsearches.forEach(dq->{
            Map<String,Object> params=new HashMap<>();
            params.put("custids", dq.getCustId());
            List<IesCust> custInfos1 = iesCustMapper.selectByMap(params);
            if(custInfos1!=null&&custInfos1.size()>0){
                String consId = dq.getConsId();
                Map<String,Object> param=new HashMap<>();
                param.put("cons_id",consId);
                param.put("type","down1");
                List<DgjDown> dgjDowns = dgjDownMapper.selectByMap(param);
                String jffs="";
                if(dgjDowns!=null&&dgjDowns.size()>0){
                    jffs=dgjDowns.get(0).getBaCalcMode();
                }
                IesCustConsno iesCustConsno=new IesCustConsno();
                iesCustConsno.setConsno(dq.getConsNo());
                iesCustConsno.setCustid(custInfos1.get(0).getCustid());
                iesCustConsno.setConid(sf.nextId()+"");//	bigint	19	0	N	Y		用户标识1
                iesCustConsno.setOrgno(dq.getOrgNo());	//varchar	50	0	Y	N		供电单位编号
                iesCustConsno.setConsname(dq.getConsName());	//varchar	50	0	Y	N		用户名称
                iesCustConsno.setElectypecode(dq.getElecTypeCode());	;//varchar	8	0	Y	N		用电类别
                iesCustConsno.setRuncap(dq.getRunCap());	//decimal	16	6	Y	N		运行容量（kVA）
                iesCustConsno.setStatus(dq.getStatusCode());	//varchar	8	0	Y	N		用电客户状态（服务中、待启动）
                iesCustConsno.setBasecostmodel(jffs);//	varchar	50	0	Y	N		基本费计算方式
                String voltlevel="";
                if("01".equals(dq.getVoltCode())){
                    voltlevel="AC00101";
                }
                if("02".equals(dq.getVoltCode())){
                    voltlevel="AC00351";
                }
                if("03".equals(dq.getVoltCode())){
                    voltlevel="AC01101";
                }
                if("04".equals(dq.getVoltCode())){
                    voltlevel="AC02201";
                }
                if("".equals(voltlevel)){
                    voltlevel=dq.getVoltCode();
                }
                iesCustConsno.setVoltlevel(voltlevel);	//varchar	8	0	Y	N		电压等级


                iesCustConsno.setPowerfactor("");	//decimal	16	6	Y	N		功率因数
                iesCustConsnoMapper.insert(iesCustConsno);
            } else {
                log.info("iesCustConsnoerr:{}","营销用户的客户id不存在");
                log.info("iesCustConsno:{}", JSONObject.toJSON(dq));
            }
        });
        powerfactor();

    }

    /**
     * 更新iesCustConsno功率因数字段
     */
    public void powerfactor() {
       List<IesCustConsno> iesCustConsnos=iesCustConsnoMapper.selectAll();
       List<String> s=new ArrayList<>();
        iesCustConsnos.forEach(l->{
            String consno = l.getConsno();
            Map<String,Object> param=new HashMap<>();
            param.put("cons_no",consno);
            List<DgjAfteraddsearch> dgjAfteraddsearches = dgjAfteraddsearchMapper.selectByMap(param);
            if(dgjAfteraddsearches!=null&&dgjAfteraddsearches.size()>0){
                Map<String,Object> map=new HashMap<>();
                map.put("cons_id",dgjAfteraddsearches.get(0).getConsId());
                map.put("type","down2");
                List<DgjDown> dgjDowns = dgjDownMapper.selectByMap(map);
                dgjDowns.forEach(d->{
                    String pfStdCode = d.getPfStdCode();
                    if(pfStdCode!=null&&pfStdCode.indexOf("考核标准")>-1){
                        pfStdCode=  pfStdCode.replace("考核标准","");
                        StringBuilder sb1=new StringBuilder("UPDATE `ies_cust_consno` i SET powerfactor='");
                        StringBuilder sb3=new StringBuilder("' WHERE consno='");
                        StringBuilder sb5=new StringBuilder("';");
                        StringBuilder append = sb1.append(pfStdCode).append(sb3).append(consno).append(sb5);
                        s.add(append.toString());
                      //  log.info("s:{}",append);
                    }
                 //   log.info("pfStdCode:{}",pfStdCode);
                });
            }
        });
        log.info("sList:{}",s);
    }
    @Autowired
    private TSysOrgMapper tSysOrgMapper;
    private void addCustInfo(SnowFlake sf) {
        //所有的电管家的客户信息
        List<CustInfo> custInfos = custInfoMapper.selectAll();
        custInfos.forEach(custInfo->{
            IesCust iesCust=new IesCust();
            iesCust.setCustids(custInfo.getCustId());
            iesCust.setCustid(sf.nextId()+"");
            iesCust.setCustencoded(custInfo.getCustNo());
            iesCust.setCustname(custInfo.getCustName());
            makeTax(custInfo, iesCust);
            makeAddr(custInfo, iesCust);
            iesCust.setLongitude(custInfo.getLongData()); //经纬度
            iesCust.setLatitude(custInfo.getLatiData());
            String orgNo = custInfo.getOrgNo();

            iesCust.setOrgno(orgNo);
            if(orgNo!=null&&!"".equals(orgNo)){
                Map<String,Object> param=new HashMap<>();
                param.put("code",orgNo);
                List<TSysOrg> tSysOrgs = tSysOrgMapper.selectByMap(param);
                if(tSysOrgs!=null&&tSysOrgs.size()>0){
                    TSysOrg tSysOrg = tSysOrgs.get(0);
                    iesCust.setOrgname(tSysOrg.getName());
                }
            }
            iesCust.setTradecode(custInfo.getTradeCode());
            iesCust.setServerstartdate(custInfo.getServiceBgn());//服务开始时间
            iesCust.setServerenddate(custInfo.getServiceEnd());//服务结束时间
            iesCust.setStatus(custInfo.getStatusCode());
            makeConnectionmode(custInfo, iesCust);
            makeContact(custInfo, iesCust);
            iesCust.setIsimportant("0");//默认 不是重点企业  之前的数据中没有该字段
            iesCust.setCusttype(custInfo.getElecTypeCode());//用电类型
            iesCust.setRegisterfax("");
            iesCust.setCreate_byname("电管家导入");
           // iesCust.setCreate_by();
            iesCust.setCreate_date(custInfo.getCreateTime());
            iesCust.setCustsettype(custInfo.getCustType());
           // iesCusts.add(iesCust);
            iesCustMapper.insert(iesCust);
            log.info(custInfo.getCustId());
        });
        // UPDATE `ies_cust_djz20230316` i,`dgj_down` d SET i.type_code_name=d.type_code_name WHERE  d.type='down1' AND i.custids=d.cust_id;
        iesCustMapper.updateTypeCodeName();
    }

    private void makeConnectionmode(CustInfo custInfo, IesCust iesCust) {
        Map<String,Object> params=new HashMap<>();
        params.put("cust_id", custInfo.getCustId());
        List<DgjQuerysitegrid> dgjQuerysitegrids = dgjQuerysitegridMapper.selectByMap(params);
        if(dgjQuerysitegrids!=null&&dgjQuerysitegrids.size()>0){
            StringBuilder sb=new StringBuilder();
            dgjQuerysitegrids.forEach(d->{
                if(d.getWiringCode()!=null&&!"".equals(d.getWiringCode())){
                    sb.append(d.getWiringCode()).append(",");
                }
            });
            if(sb.length()>=1){
                sb.substring(0,sb.length()-1);
                iesCust.setConnectionmode(sb.toString());//厂站管理中的接线方式
            }
        }
    }
    @Autowired
    private TSysRegionMapper tSysRegionMapper;
    private void makeAddr(CustInfo custInfo, IesCust iesCust) {
        Map<String,Object> params=new HashMap<>();
        params.put("cust_id", custInfo.getCustId());
        List<CustAddr> custAddrs = custAddrMapper.selectByMap(params);
        if(custAddrs!=null&&custAddrs.size()>0){
            CustAddr custAddr = custAddrs.get(0);
            if(custAddr.getProvinceCode()!=null&&!"".equals(custAddr.getProvinceCode())){
                TSysRegion tSysRegion = tSysRegionMapper.selectById(custAddr.getProvinceCode());
                if(tSysRegion!=null){
                    iesCust.setCustprovince(tSysRegion.getName());//省份 在地址信息中
                }
            }
            if(custAddr.getCityCode()!=null&&!"".equals(custAddr.getCityCode())){
                TSysRegion tSysRegion = tSysRegionMapper.selectById(custAddr.getCityCode());
                if(tSysRegion!=null){
                    iesCust.setCustcity(tSysRegion.getName());//市份 在地址信息中
                }
            }
            if(custAddr.getCountyCode()!=null&&!"".equals(custAddr.getCountyCode())){
                TSysRegion tSysRegion = tSysRegionMapper.selectById(custAddr.getCountyCode());
                if(tSysRegion!=null){
                    iesCust.setCustcounty(tSysRegion.getName());//县级 在地址信息中
                }
            }
             iesCust.setRegioncode(custAddr.getProvinceCode()+","+custAddr.getCityCode()+","+custAddr.getCountyCode());
              iesCust.setConsaddr(custAddr.getCustAddr()); //在地址信息中 增值税信息中也有地址
              iesCust.setPostaddr(custAddr.getCustAddr());// 邮寄地址 在地址信息中 增值税信息中也有地址

        }
    }

    private void makeContact(CustInfo custInfo, IesCust iesCust) {
        Map<String,Object> params=new HashMap<>();
        params.put("cust_id", custInfo.getCustId());
        List<DgjInitupdcontact> dgjInitupdcontacts = dgjInitupdcontactMapper.selectByMap(params);
        if(dgjInitupdcontacts!=null&&dgjInitupdcontacts.size()>0){
             iesCust.setEmail(dgjInitupdcontacts.get(0).getEmail()); //联系人信息中  有邮箱
             iesCust.setContactperson(dgjInitupdcontacts.get(0).getContactName()); //联系人信息中 联系人
             iesCust.setContactphone(dgjInitupdcontacts.get(0).getMobile());// 联系人信息中 联系电话
        }
    }

    private void makeTax(CustInfo custInfo, IesCust iesCust) {
        Map<String,Object> param=new HashMap<>();
        param.put("cust_id", custInfo.getCustId());
        List<Tax> taxes = taxMapper.selectByMap(param);
        if(taxes!=null&&taxes.size()>0){
            Tax tax = taxes.get(0);
            iesCust.setSocialunifiedcreditcode(tax.getVatNo());//统一信用代码 在增值税信息中
             iesCust.setDepositbank(tax.getBankName());//在增值税信息中 开户银行
             iesCust.setDepositbankaccount(tax.getVatAcct());
             iesCust.setRegisterddr(tax.getRegAddr());
             iesCust.setRegistertel(tax.getRegTel());
        }
    }

    /**
     * 更新用电类型
     */
    public void elecTypeCode() {
        List<CustInfo> custInfos = custInfoMapper.selectAll();
        List<String> l=new ArrayList<>();
        custInfos.forEach(c->{
            String custNo = c.getCustNo();
            String elecTypeCode = c.getElecTypeCode();
            String sql="UPDATE `ies_cust` i SET custtype='"+elecTypeCode+"' WHERE custno='"+custNo+"';";
            l.add(sql);
        });
        log.info("l:{}",l);
    }
}
